import { Button, Row, Col, Typography } from 'antd';
import { useEffect, useState } from 'react';
import styles from './index.less';
import { request, Helmet } from 'umi';
import { history } from '@@/core/history';

const { Text } = Typography;

export default function IndexPage() {
  const [title, setTitle] = useState('加载中...');
  const [sites, setSites] = useState([]);
  const [shops, setShops] = useState({});
  const [shop, setShop] = useState('');
  const [footer, setFooter] = useState({
    slogan: '',
    copyright: '',
  });

  useEffect(() => {
    if (history.location.search) {
      const key = history.location.search.split('=');
      setShop(key[1]);
    }

    request('./data.json').then((res) => {
      setTitle(res.title);
      setFooter(res.footer);
      setSites(res.data);
      setShops(res.shops);
    });
  }, []);

  const date = new Date();

  const filterShops = (itemName: string) => {
    if (shop && shops) {
      const shopName = shops[shop];
      if (shopName) {
        return shopName.includes(itemName);
      }
      return false;
    }
    return true;
  };

  return (
    <>
      <Helmet>
        <title>{title}</title>
      </Helmet>
      <div className={styles.content}>
        <div className={styles.header}>
          <div className={styles.logo}>
            <img style={{ width: '100%' }} src={require('@/images/logo.png')} alt="logo" />
          </div>
        </div>
        {sites.map((item: { title: string; name: string; children: any }) => (
          <div key={item.name}>
            {filterShops(item.name) && (
              <div className={styles.nav}>
                <div style={{ paddingBottom: '5px' }}>
                  <Text type="secondary">{item.title}</Text>
                </div>
                <Row gutter={[10, 10]}>
                  {item.children.map((subItem: { name: string; url: string }) => (
                    <Col xs={12} sm={8} md={6} lg={4} key={subItem.name}>
                      <Button
                        type="primary"
                        size="large"
                        href={subItem.url}
                        target="_blank"
                        block
                        ghost
                      >
                        {subItem.name}
                      </Button>
                    </Col>
                  ))}
                </Row>
              </div>
            )}
          </div>
        ))}
        {sites.length > 0 && (
          <div className={styles.footer}>
            <Text type="secondary" style={{ fontSize: '16px' }}>
              {footer.slogan}
            </Text>
            <br></br>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              © {date.getFullYear()} {footer.copyright}
            </Text>
          </div>
        )}
      </div>
    </>
  );
}
